#include "imagescroller.h"
#include "imagestructure.h"


ImageScroller::ImageScroller( QWidget* parent )
	: QListWidget( parent )
{
	//////TestLoad();
	setIconSize ( QSize(80,80));
	connect(this, SIGNAL(clicked(const QModelIndex &)),this, SLOT(Activate(const QModelIndex&)));
	connect(this, SIGNAL(clicked(const QModelIndex &)),this, SLOT(Activate(const QModelIndex&)));
	Onselectrow = -1;
  setContentsMargins ( 5, 5, 5, 5 );
	shortcut0 = new QShortcut(QKeySequence("Ctrl+V"),this);
	connect(shortcut0, SIGNAL(activated()),this, SLOT(PasteImage()));
  setViewMode ( QListView::IconMode  );
	QListWidget::setResizeMode ( QListView::Adjust );
	setContextMenuPolicy(Qt::DefaultContextMenu);
	
  QListWidget::setAcceptDrops ( true );
  setAcceptDrops ( true );
  
}


void ImageScroller::in_image( int id )
{
	
	LoadGetImage *ht = qobject_cast<LoadGetImage *>(sender());
	  
	   QPixmap  imagen = ht->pics();
	
						           if (!imagen.isNull()) {
						           const QString nami = QString("Name_Paste_%1").arg(QTime_Null());
					             SPics  xpix;
					             xpix.name = nami;
					             xpix.set_pics(imagen);
					             AppendImage(xpix);
											 }
	
	
	
}

void ImageScroller::dropEvent ( QDropEvent * e )   
{
	  ///  QMimeData
	  QList<QUrl> urls = e->mimeData()->urls();
	   qDebug() << "### urls " << urls.size();
	    for ( int i = 0; i < urls.size(); ++i ) { 
          QUrl gettyurl(urls.at(i));
				  qDebug() << "### gettyurl " << gettyurl.toString();
				  if (gettyurl.scheme() == "file") {
						           QPixmap  imagen(gettyurl.toLocalFile());
						           if (!imagen.isNull()) {
						           const QString nami = QString("Name_Paste_%1").arg(QTime_Null());
					             SPics  xpix;
					             xpix.name = nami;
					             xpix.set_pics(imagen);
					             AppendImage(xpix);
											 }
											 
					} else if (gettyurl.scheme() == "http") {
						
						                Gloader *grephttp = new Gloader();
							              grephttp->Setting(this,i,gettyurl); 
							              grephttp->start(QThread::LowPriority);
						
					}
				
			}
	
}

void ImageScroller::dragEnterEvent( QDragEnterEvent * e )   
{
	  ///  QMimeData
	  QList<QUrl> urls = e->mimeData()->urls();
	   qDebug() << "### urls 3" << urls.size();
	  if (urls.size() > 0) {
			e->accept();
		}

	
} 

void ImageScroller::dragMoveEvent ( QDragMoveEvent * e )   
{
	  ///  QMimeData
	  QList<QUrl> urls = e->mimeData()->urls();
	   qDebug() << "### urls 4 " << urls.size();
	  if (urls.size() > 0) {
			e->accept();
		}

	
} 




///TContext->addAction(tr( "Esporta come gruppo immagini" ), this , SLOT( ExportFile() ) );
		//////		TContext->addAction(tr( "Importa da gruppo immagini file" ), this , SLOT( ImportFile() ) );

QString ImageScroller::streamSave()
{
	if (model()->rowCount() < 0) {
		return QString();
	}
	
	if ( kilosize() > MAXUPLOADKILO ) {
		QMessageBox::information(0, tr("Error image file."),tr("You have to many file size: limit are %1").arg(KMega(MAXUPLOADKILO)));
		return QString();
	}
	
	
	QList<SPics> li;
	      for (int e = 0; e < model()->rowCount(); ++e) {
					QListWidgetItem *dove = item( e );
	        SPics Io = dove->data(Qt::UserRole).value<SPics>();
					li.append(Io);
				}
				
		return SaveImageGroup(li);
}

int  ImageScroller::kilosize()
{
	if (model()->rowCount() < 0) {
		return 0;
	}
	int kilo = 0;
	      for (int e = 0; e < model()->rowCount(); ++e) {
					QListWidgetItem *dove = item( e );
	        SPics Io = dove->data(Qt::UserRole).value<SPics>();
					kilo = Io.picskilo() + kilo;
				}
				
		return kilo;
}



void ImageScroller::ExportFile()
{
	if (model()->rowCount() < 0) {
		QMessageBox::warning(0, tr("Error Image list"),tr("No item found!"));
		return;
	}
	QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("Image Group file (*.qzpic)"));
	
	
		if (!fileName.isEmpty() ) {
		    if (!fileName.endsWith(".qzpic")) {
            fileName.append(".qzpic");
        } 
				const QString dati = streamSave();
				QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << dati;
        f.close();
        }
	}
	
	
}

void ImageScroller::importStream( const QString inside )
{
	
	QList<SPics> li = OpenImageGroup(inside);
								
							  if (li.size() > 0) {
									clear();
								}
								for (int i=0; i<li.size(); i++) {
                  SPics conni = li[i];
									AppendImage(conni);
                } 
	
}


void ImageScroller::ImportFile()
{
	QString fixfile = QFileDialog::getOpenFileName(this, tr("Importa - Apri file"),
	                          QCoreApplication::applicationDirPath(),
	                                         "Image Group file (*.qzpic)" );
    if (!fixfile.isEmpty()) {
			
			  QString inside;
			  QFile file(fixfile); 
								if (file.exists()) {
														if (file.open(QFile::ReadOnly | QFile::Text)) {
																inside = QString::fromUtf8(file.readAll());
															  file.close();
														}
								}
				importStream( inside );
		}
	
	
}




void ImageScroller::PasteImage()
{
	 const QMimeData *data =  QApplication::clipboard()->mimeData();
        if (data->hasImage() ) {
                QImage images = qvariant_cast<QImage>(data->imageData());
					      const QString nami = QString("Name_Paste_%1").arg(QTime_Null());
					      SPics  xpix;
					             xpix.name = nami;
					             xpix.set_pics(QPixmap::fromImage(images));
					             AppendImage(xpix);
        }
}

void ImageScroller::AppendImage( SPics pic )
{
	        QString tmpname = pic.name;
	        tmpname.resize(6);
					QListWidgetItem * item = new QListWidgetItem( QIcon(pic.pix()),tmpname);
					
	        QPixmap mesu = pic.pix();
	        if ( mesu.width() > _MAX_IMAGE_WIDTH_) {
						QPixmap rewrite = mesu.scaledToWidth(_MAX_IMAGE_WIDTH_,Qt::SmoothTransformation);
						  if (!rewrite.isNull()) {
								pic.set_pics(rewrite);
								item->setData(Qt::UserRole,pic);
								item->setToolTip(pic.info + " " +KMega(pic.picskilo()));
								insertItem(model()->rowCount(),item);
							}
						
					} else {
						item->setData(Qt::UserRole,pic);
						item->setToolTip(pic.info + " " +KMega(pic.picskilo()));
						insertItem(model()->rowCount(),item);
					}
					
	
	     QListWidget::setResizeMode ( QListView::Adjust );
	
	
	if ( kilosize() > MAXUPLOADKILO ) {
		QMessageBox::information(0, tr("Error image file."),tr("You have to many file size: limit are %1").arg(KMega(MAXUPLOADKILO)));
		//////////return QString();
	}
}

void ImageScroller::Activate( const QModelIndex &index ) 
{
        if (!index.isValid()) {
        return;  
        }
        SPics Io = index.data(Qt::UserRole).value<SPics>();
				if (ACTIVENAME == Io.name) {
				return;
				}
				attuale = index;
				Onselectrow =  index.row();
				ACTIVENAME = Io.name;
				///////////qDebug() << "### name " << Io.name;
				///////////qDebug() << "### line " << Onselectrow;
				current = Io.pix();
				emit Redraw();
				//////////  
}
void ImageScroller::EsportaPic()
{
	QString ext = "*.png";
	QString Bname;
	QPixmap imo;
	if (Onselectrow !=-1) {
		
				QListWidgetItem *dove = item( Onselectrow );
	      SPics Io = dove->data(Qt::UserRole).value<SPics>();
				imo = Io.pix();
		
              QAction *invoice = qobject_cast<QAction *>(sender());
              const QString extension = invoice->data().toString();
		          if (extension == "JPG") {
								ext = "*.jpg";
								Bname = Io.name + ".jpg";
							} else {
								Bname = Io.name + ".png";
							}
		
						QString fileName = QFileDialog::getSaveFileName(0, "Image file",QString(setter.value("LastDir").toString()+Bname),ext);
            if (fileName.size() > 1) {
							
							setter.setValue("LastDir",fileName.left(fileName.lastIndexOf("/"))+"/");
                    
                  if (extension == "JPG") {
                    imo.save(fileName,"JPG",100);
									} else {
                    imo.save(fileName,"PNG",100);
									}										
            }
	}
}


void ImageScroller::contextMenuEvent ( QContextMenuEvent * e )
{
	  
	  QAction *open0 = new QAction(tr("Esporta come PNG"),this);
    open0->setStatusTip(tr("Esporta come PNG"));
	  open0->setData("PNG");
    connect(open0, SIGNAL(triggered()), this,  SLOT(EsportaPic()));
	
	  QAction *open1 = new QAction(tr("Esporta come JPG"),this);
    open1->setStatusTip(tr("Esporta come JPG"));
	  open1->setData("JPG");
    connect(open1, SIGNAL(triggered()), this,  SLOT(EsportaPic()));
	
	
	  QMenu *TContext = new QMenu();
		TContext->addAction(tr( "Descrizione immagine..." ), this , SLOT( NewDesc() ) );
	  TContext->addAction(tr( "Aggiungi immagine..." ), this , SLOT( AppendPics() ) );
    TContext->addAction(tr( "Rimpiazza corrente con..." ), this , SLOT( ReplacePic() ) );
		TContext->addAction(tr( "Cancellare immagine" ), this , SLOT( RemFile() ) );
		TContext->addSeparator ();
	
	     const QMimeData *data =  QApplication::clipboard()->mimeData();
        if (data->hasImage() ) {
					QImage images = qvariant_cast<QImage>(data->imageData());
					
					TContext->addAction(QIcon(QPixmap::fromImage(images)),tr( "Incolla CTRL+V" ), this , SLOT( PasteImage() ) );
        }
	
	
	
	
	
	
	  TContext->addAction(open0);
	  TContext->addAction(open1);
				TContext->addSeparator ();
				TContext->addAction(tr( "Esporta come gruppo immagini" ), this , SLOT( ExportFile() ) );
				TContext->addAction(tr( "Importa da gruppo immagini file" ), this , SLOT( ImportFile() ) );
				
				
				
    TContext->exec(QCursor::pos());
    open0->deleteLater();
		open1->deleteLater();
    TContext->deleteLater();
    delete TContext;
}
 


/////////void ImageScroller::resizeEvent ( QResizeEvent * e )   
/////////{
	
	/////////update(viewport()->rect());
	//////setViewMode ( QListView::IconMode  );
	////////setViewMode ( QListView::IconMode  );
/////////}

/*


*/

void ImageScroller::ReplacePic()
{
	QPixmap resultimage;
	
	if (Onselectrow !=-1) {
		
				resultimage = AppendImageGeneral();
		    if ( resultimage.isNull() ) {
				return;
			  }
	      QListWidgetItem *dove = item( Onselectrow );
	      SPics Io = dove->data(Qt::UserRole).value<SPics>();
				Io.set_pics(resultimage);
				dove->setData(Qt::UserRole,Io);
				dove->setIcon ( QIcon(resultimage) );
				QApplication::restoreOverrideCursor();
	}
}




void ImageScroller::NewDesc()
{

	if (Onselectrow !=-1) {
	      QListWidgetItem *dove = item( Onselectrow );
	      SPics Io = dove->data(Qt::UserRole).value<SPics>();
				QString notatxt = QInputDialog::getText(this, tr("Informazioni non vedenti."),tr("Descrizione:"), QLineEdit::Normal,Io.info);
				if (notatxt.size() > 0) {
					Io.info = notatxt;
					dove->setData(Qt::UserRole,Io);
					dove->setToolTip(Io.info);
				}
				QApplication::restoreOverrideCursor();
	}
}

//////////////////  QString SaveImageGroup( QList<SPics> li  )


void ImageScroller::RemFile()
{
	if (Onselectrow !=-1) {
		
		/////////////qDebug() << "### rem Onselectrow " << Onselectrow;
		
		QListWidgetItem *ss = takeItem ( Onselectrow );
		delete ss;
		//////QListWidgetItem *dove = item( Onselectrow );
	  /////bool xx = model()->removeRows ( Onselectrow , 0 , attuale );
		/////qDebug() << "### rem xx  " << xx;
	}
	
}



void ImageScroller::AppendPics()
{
	
		
				QPixmap resultimage = AppendImageGeneral();
		    if ( resultimage.isNull() ) {
				return;
			  }
				const QString nami = QString("Name_%1").arg(QTime_Null());
					      SPics  xpix;
					             xpix.name = nami;
					             xpix.set_pics(resultimage);
					             AppendImage(xpix);

}


QPixmap ImageScroller::AppendImageGeneral()
{
	     QPixmap                 resultimage;
	
			const QString filter = ImageFilterHaving();
		   QString file = QFileDialog::getOpenFileName( this, tr( "Scegli una immagine..." ), QString(setter.value("LastDir").toString()) , filter );
       if ( file.isEmpty() ) {
          return resultimage;
        }
				
		 setter.setValue("LastDir",file.left(file.lastIndexOf("/"))+"/");
		 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
     QFileInfo fixurl(file);
     const QString extension =  fixurl.completeSuffix().toLower();
     QByteArray              derangedata;
     
     QPixmap                 scaledsimage;
     QUrl                    imgresor;
				
				
				if (extension.contains(".gz")) {
        ///////derangedata = OpenGzipOneFileByte( fixurl.absoluteFilePath() );
				QApplication::restoreOverrideCursor();
        return resultimage;
        } else {
                         QFile f(fixurl.absoluteFilePath());
                         if (f.open(QIODevice::ReadOnly)) {
                            derangedata = f.readAll();
                            f.close();
                         }
        }
				
				if (derangedata.size() < 1) {
        QApplication::restoreOverrideCursor();
        QMessageBox::critical( this, tr( "Alert! image format." ), tr( "Unable to read file %1" ).arg(fixurl.fileName()) );  
        return resultimage;
        }
				
				      /* read image */
        if (extension.contains("sv")) {
        resultimage = RenderPixmapFromSvgBy(  derangedata );
        } else if (extension.contains("ps") || extension.contains("eps")) {
        resultimage = LoadPS( fixurl.absoluteFilePath() );
        } else if (extension.contains("pdf")) {
					
            QApplication::restoreOverrideCursor();
            int page = QInputDialog::getInteger(this, tr("Render Page Nr."),tr("Page:"),1, 1, 100, 1);
            int large = QInputDialog::getInteger(this, tr("Page scaled to width"),tr("Point unit:"),1500, 10, 3000, 10);
            if (page > 0 && large > 0) {
                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
                resultimage = LoadPDF( fixurl.absoluteFilePath() ,page,large);
            } else {
                QApplication::restoreOverrideCursor();
            return resultimage;
            }
        }  else {
					
        resultimage.loadFromData( derangedata );
        }
				
				  /* read in */
        if ( resultimage.isNull() ) {
        QApplication::restoreOverrideCursor();
        QMessageBox::critical( this, tr( "Alert! image format." ), tr( "Unable to render to image file %1 from type %2." ).arg(fixurl.fileName()).arg(extension) ); 
        return resultimage;
        }
				QApplication::restoreOverrideCursor();
				return resultimage;
	
}


void ImageScroller::TestLoad()
{
        for (int i=0; i<3; i++) {
						const QString nami = QString("Name_%1").arg(i);
					  SPics  xpix;
					         xpix.set_pics( TestImage( nami) );
					         xpix.name = nami;
					         AppendImage( xpix );
         }
}






ImageList::ImageList( QWidget* parent )
	: QWidget( parent )
{
	  resize(700,120);
    gridLayout = new QGridLayout(this);
    groupBox = new QGroupBox(tr("Immagini associate:"),this);
    gridLayout1 = new QGridLayout(groupBox);
    /* verticale */
    vboxLayout = new QVBoxLayout();
    label = new QLabel(tr("Lista:"),groupBox);
    vboxLayout->addWidget(label);
    lista = new ImageScroller(groupBox);
    lista->setMaximumSize(QSize(350, 16777215));
	  setMinimumSize(QSize(120,80));
    vboxLayout->addWidget(lista);
    /* verticale */
	
	  gridLayout1->addLayout(vboxLayout, 0, 0, 1, 1);
	
	
	      /* verticale */
    vboxLayout1 = new QVBoxLayout();
    label_2 = new QLabel(tr("Immagine zoom ...."),groupBox);
    vboxLayout1->addWidget(label_2);
	  scrolla = new Opscroll(groupBox);
		scrolla->setMinimumSize(QSize(450,80));
		scrolla->setBackgroundRole(QPalette::Dark);
		
		wrapper = new Foto_DD(this);  
    scrolla->setWidget(wrapper);
    vboxLayout1->addWidget(scrolla);
		/* verticale */
		
		
    gridLayout1->addLayout(vboxLayout1, 0, 1, 1, 1);
    gridLayout->addWidget(groupBox, 0, 0, 1, 1);
    
	  connect(lista, SIGNAL(Redraw()), this, SLOT(FillImage()));
		connect(scrolla, SIGNAL(Tick(int)), this, SLOT(Wheelgo(int)));
		
	
}


void ImageList::FillImage()
{
	Original = lista->cur();
	//////qDebug() << "####### swapimage  " << Original.isNull(); 
	QRect screenSize = qApp->desktop()->availableGeometry();
	wrapper->setMinimumSize(screenSize.size());
	SetZoom(80);
}

void ImageList::SetZoom( int percentual )
{
    
    /////////qDebug() << "####### percentual  " << percentual; 
    if (Original.isNull()) {
    return;
    }
		if (percentual < 0) {
		ratio = 10;
		SetZoom(ratio);
		return;
		}
    ////////qDebug() << "####### percentual  " << percentual; 
    ratio = percentual;
    
		label_2->setText(tr("Immagine zoom %1% dimensioni reali %2x%3 px")
		                    .arg(percentual)
		                    .arg(Original.width())
		                    .arg(Original.height()));
		
    int newlarge = (Original.width()/100.00)*percentual;
		
		/////////qDebug() << "####### newlarge  " << newlarge; 
		
    QPixmap display = Original.scaledToWidth(newlarge,Qt::FastTransformation);
    wrapper->paint(display);
    scrolla->setWidget(wrapper);
}



void ImageList::wheelEvent(QWheelEvent *event)
{
    int numDegrees = event->delta() / 8;
    int numTicks = numDegrees / 15;
    Wheelgo(numTicks);
    return;
}

void ImageList::Wheelgo(int numTicks )
{
	/////////qDebug() << "###  wheelEvent numTicks " << numTicks;
	  if (numTicks == 1) {
        int pluspuls = ratio + 1;
    SetZoom(pluspuls);
    } else {
        int minuspuls = ratio - 1;
     SetZoom(minuspuls); 
    }
}


LoadGetImage::LoadGetImage( int nr , QUrl url_send  )
	: QHttp(url_send.host(),QHttp::ConnectionModeHttp ,80)
{
     url = url_send;
     cid = nr;
     setHost(url_send.host() , 80);
	    /////qDebug() << "### parte -> " << url;
}

void LoadGetImage::Start()
{
	     const QString METHOD =  "GET";
       const QString agent = QString("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
			 header.setRequest(METHOD,url.path(),1,1);
			 header.setValue("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			 header.setValue("Host",url.host());
			 header.setValue("User-Agent",agent);
			 connect(this, SIGNAL(done(bool)), this , SLOT(ImageReady(bool)));
       Http_id = request(header,0,0);
}

void LoadGetImage::ImageReady( bool error )
{
    if (!error) {
        resultimage.loadFromData(readAll());
                if (!resultimage.isNull()) {
                    emit take(cid);
                }
        
     
    }
}



void Gloader::Setting( QObject *parent , int id , QUrl url_send )
{
	receiver = parent;
	cid = id;
	url = url_send;
	setTerminationEnabled(true);
}

void Gloader::run()
{
	 Rhttp = new LoadGetImage(cid,url);
	 connect(Rhttp, SIGNAL(take(int)), receiver , SLOT(in_image(int)));
	 Rhttp->Start();
	 exec();
}













